var app = getApp();
var api = require('../../api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    flowarray: [],
    index: 0,
    images: [],
    id: 0,
    currentTab: 0,
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0
    },
    img: "",
    img_list: [],
    info: {},
    head:'',
    avatar:''  
    },


  //navbar，菜单切换
  tabFun: function (e) {
    //获取触发事件组件的dataset属性  
    var _datasetId = e.target.dataset.id;
    console.log("----" + _datasetId + "----");
    var _obj = {};
    _obj.curHdIndex = _datasetId;
    _obj.curBdIndex = _datasetId;
    this.setData({
      tabArr: _obj
    });
  },

  /*选择费用类型*/
  flowChange: function (e) {
    this.setData({
      index: e.detail.value,
      type: this.data.flowarray[e.detail.value].key
    });
  },

  select_date: function (e) {
    this.setData({
      state: e.currentTarget.dataset.key,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad(options) {
    if (options) {
      var tmp_options = wx.getStorageSync("tmp_options");
      if (tmp_options) {
        wx.setStorageSync("tmp_options", Object.assign(tmp_options, options))
      } else {
        wx.setStorageSync("tmp_options", options)
      }
    }
    this.getApplyInfo();
  },
  //绑定输入

  inputTel: function (e) {
    this.setData({
      tel: e.detail.value
    })
  },
  inputName: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  inputTitle: function (e) {
    this.setData({
      title: e.detail.value
    })
  },
  inputDec: function (e) {
    this.setData({
      dec: e.detail.value
    })
  },
  inputPrice: function (e) {
    this.setData({
      price: e.detail.value
    })
  },
  //上传头像
  portrait:function(e) {
    var that = this;
    var max_count = 1;
    var head = this.data.head;
  //  var current_count = img_list.length;
    wx.chooseImage({
      sizeType: ['original'],
      sourceType: ['album'],
      success: function(res) {
        head =head.concat(res.tempFilePaths);

        var form_id = e.detail.formId;
        if (head.length == 0) {
          wx.showModal({
            title: '提示',
            content: '请输入内容或上传图片',
            showCancel: false
          })
          return false;
        }
        wx.showLoading({
          title: '正在提交',
          mask: true
        });
        uploadImg(0);
        //上传封面
        function uploadImg(i) {
          
          wx.uploadFile({
            url: api.default.upload_img,
            filePath: head,
            name: 'image',
            complete: function (res) {
              if (res.statusCode == 200) {
                var data = JSON.parse(res.data);
                if (data.errcode == 0) {
                  wx.showToast({
                    title: '上传成功',
                  });
                  that.setData({
                    avatar: data.data.url
                  });

                } else {
                  wx.showToast({
                    title: '上传失败',
                    icon: 'none'
                  });
                }
              } else {
                wx.showToast({
                  title: '上传失败',
                  icon: 'none'
                });
              }

            }
          })

        } 
      },
    })
  },



  //选择图片
  chooseImage(e) {
    var that = this;
    var max_count = 1;
    var img_list = this.data.img_list;
    var current_count = img_list.length;
    wx.chooseImage({
      count: (max_count - current_count),
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        img_list = img_list.concat(res.tempFilePaths);

        var upload_img = [];

        var form_id = e.detail.formId;
        if (img_list.length == 0) {
          wx.showModal({
            title: '提示',
            content: '请输入内容或上传图片',
            showCancel: false
          })
          return false;
        }
        wx.showLoading({
          title: '正在提交',
          mask: true
        });

        uploadImg(0);
        //上传封面
        function uploadImg(i) {
          wx.uploadFile({
            url: api.default.upload_img,
            filePath: img_list[i],
            name: 'image',
            complete: function (res) {
              if (res.statusCode == 200) {
                var data = JSON.parse(res.data);
                if (data.errcode == 0) {
                  wx.showToast({
                    title: '上传成功',
                  });
                  that.setData({
                    img: data.data.url
                  });

                } else {
                  wx.showToast({
                    title: '上传失败',
                    icon: 'none'
                  });
                }
              } else {
                wx.showToast({
                  title: '上传失败',
                  icon: 'none'
                });
              }

            }
          })

        }
      },
    })
  },
  avatarImage(e){
    this.setData({
      avatar: ''
    })
  },

  removeImage(e) {
    this.setData({
      img: ''
    })
  },

  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    const images = this.data.images
    wx.previewImage({
      current: images[idx], //当前预览的图片
      urls: images, //所有要预览的图片
    })
  },

  submitForm(e) {
    const title = this.data.title
    const content = this.data.content

    if (title && content) {
      const arr = []

      //将选择的图片组成一个Promise数组，准备进行并行上传
      for (let path of this.data.images) {
        arr.push(wxUploadFile({
          url: config.urls.question + '/image/upload',
          filePath: path,
          name: 'qimg',
        }))
      }

      wx.showLoading({
        title: '正在创建...',
        mask: true
      })

      // 开始并行上传图片
      Promise.all(arr).then(res => {
        // 上传成功，获取这些图片在服务器上的地址，组成一个数组
        return res.map(item => JSON.parse(item.data).url)
      }).catch(err => {
        console.log(">>>> upload images error:", err)
      }).then(urls => {
        // 调用保存问题的后端接口
        return createQuestion({
          title: title,
          content: content,
          images: urls
        })
      }).then(res => {
        // 保存问题成功，返回上一页（通常是一个问题列表页）
        const pages = getCurrentPages();
        const currPage = pages[pages.length - 1];
        const prevPage = pages[pages.length - 2];

        // 将新创建的问题，添加到前一页（问题列表页）第一行
        prevPage.data.questions.unshift(res)
        $digest(prevPage)

        wx.navigateBack()
      }).catch(err => {
        console.log(">>>> create question error:", err)
      }).then(() => {
        wx.hideLoading()
      })
    }
  },
  //提交
  submitApply: function () {
    var page = this
    wx.showLoading({
      title: '提交中',
    })
      app.request({
        url: api.video.applylive,
        method: 'POST',
        data: {
          apply_name: page.data.name,
          title: page.data.title,
          tel: page.data.tel,
          price: page.data.price,
          type: page.data.flowarray[page.data.index].id,
          apply_avatar: page.data.avatar,
          dec: page.data.dec,
          pic: page.data.img
        },
        success: function (res) {
          if (res.errcode == 0) {
            console.log(res);
            wx.showModal({
              title: '确定',
              content: res.errmsg,
              showCancel: false,
              confirmText: '确定',
            })
            page.setData({
              id: res.data
            })
            wx.showToast({
              title: '提交成功',
            })
            page.getApplyInfo()
          } else {
            wx.showModal({
              title: '警告',
              content: res.errmsg,
              showCancel: false
            })
          }
        },
        fail: function (res) {
          wx.showModal({
            title: '警告',
            content: res.errmsg,
            showCancel: false
          })
        },
        complete: function () {
          wx.hideLoading();
        }
      });   
  },
  //申请信息
  getApplyInfo: function () {
    var page = this;
    wx.showLoading({
      title: '加载中',
    })
    app.request({
      url: api.video.apply_info,
      method: 'POST',
      data: {},
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            info: res.data,
            name: res.data.apply_name,
            title: res.data.title,
            tel: res.data.tel,
            price: res.data.price,
            type: res.data.type,
            dec: res.data.dec,
            img: res.data.pic,
            index: res.data.type_index,
            flowarray: res.data.category,
            avatar: res.data.apply_avatar
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  //分类列表
  getClassList: function () {
    var page = this;
    wx.showLoading({
      title: '加载中',
    })
    app.request({
      url: api.video.category_select,
      method: 'POST',
      data: {},
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            flowarray: res.data
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  onShareAppMessage: function () {
    var user =wx.getStorageSync('user_info');
    return{
      url: '../live-apply/live-apply?pid=' + user.user_id
    }
  },
})